package com.yupi.project.handler;

import com.yupi.project.model.AuthenticatorResult;
import com.yupi.project.model.ProtectedRequest;
import com.yupi.project.model.RequestHolder;
import com.yupi.project.model.RequestInfo;
import com.yupi.project.security.SecurityVerificationHandler;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

/**
 * @description: 请求头参数校验
 * @author SummerBird
 * @date 2024/3/8 19:44
 * @version 1.0
 */
@Component
public class RequestParamVerificationHandler implements SecurityVerificationHandler {
    @Override
    public AuthenticatorResult auth(ProtectedRequest protectedRequest) {
        boolean checked = checkedHandler(protectedRequest.getRequest());
        if(!checked){
            return AuthenticatorResult.fail("请携带正确的请求参数");
        }
        setRequestHolder(protectedRequest);
        return AuthenticatorResult.success();
    }

    // 将后续需要反复使用的信息放入ThreadLocal中
    private void setRequestHolder(ProtectedRequest protectedRequest) {
        RequestInfo requestInfo = Optional.ofNullable(RequestHolder.get()).orElse(new RequestInfo());
        HttpHeaders headers = protectedRequest.getRequest().getHeaders();
        requestInfo.setAccessKey(headers.getFirst("accessKey"));
        requestInfo.setNonce(headers.getFirst("nonce"));
        requestInfo.setTimestamp(headers.getFirst("timestamp"));
        requestInfo.setSign(headers.getFirst("sign"));
        RequestHolder.set(requestInfo);
    }

    private boolean checkedHandler(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        return Objects.nonNull(headers.getFirst("accessKey")) &&
                Objects.nonNull(headers.getFirst("nonce")) &&
                Objects.nonNull(headers.getFirst("timestamp")) &&
                Objects.nonNull(headers.getFirst("sign"));
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
